package com.atguigu.app.dws;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.bean.UserLoginBean;
import com.atguigu.util.DateFormatUtil;
import com.atguigu.util.KafkaUtil;
import com.atguigu.util.MyClickHouseUtil;
import com.ibm.icu.util.Output;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author hefeihong
 * @version 1.0
 * @date 2022/9/3 14:13
 */
public class DwsUserUserLoginWindow {
    public static void main(String[] args) throws Exception {
        //获取环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        //设置状态后端
        /*env.enableCheckpointing(5*60*1000L, CheckpointingMode.EXACTLY_ONCE);
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.getCheckpointConfig().setCheckpointTimeout(3*60*1000L);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME","atguigu");*/

        //TODO 1 获取Kafka页面主题数据
        String topicName = "dwd_traffic_page_log";
        String groupId = "dws_user_user_login_window";
        DataStreamSource<String> streamSource = env.addSource(KafkaUtil.getKafkaConsumer(topicName, groupId));

        //TODO 2 转换数据结构为JSONObject
        SingleOutputStreamOperator<JSONObject> map = streamSource.map(JSONObject::parseObject);

        //TODO 3 过滤出登录数据

        SingleOutputStreamOperator<JSONObject> flatMap = map.flatMap(new FlatMapFunction<JSONObject, JSONObject>() {
            @Override
            public void flatMap(JSONObject value, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject common = value.getJSONObject("common");
                    JSONObject page = value.getJSONObject("page");
                    if (common.getString("uid") != null && page.getString("last_page_id") == null || "login".equals(page.getString("last_page_id"))) {
                        out.collect(value);
                    }
                }catch (Exception e){
                }
            }
        });


        //TODO 4 设置水位线
        SingleOutputStreamOperator<JSONObject> timestampsAndWatermarks = flatMap.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2L))
                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject element, long recordTimestamp) {
                        return element.getLong("ts");
                    }
                }));

        //TODO 5 按照uid 分组
        KeyedStream<JSONObject, String> keyedStream = timestampsAndWatermarks.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject value) throws Exception {
                JSONObject common = value.getJSONObject("common");
                return common.getString("uid");
            }
        });

        //TODO 6 统计当日回流用户数和当日活跃用户数
        SingleOutputStreamOperator<UserLoginBean> flatMap1 = keyedStream.flatMap(new RichFlatMapFunction<JSONObject, UserLoginBean>() {
            private ValueState<String> lastState = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                lastState = getRuntimeContext().getState(new ValueStateDescriptor<String>("lastState", String.class));
            }

            @Override
            public void flatMap(JSONObject value, Collector<UserLoginBean> out) throws Exception {
                String lastDtState = lastState.value();
                Long ts = value.getLong("ts");
                String lastDt = DateFormatUtil.toDate(ts);
                long backCt = 0L;
                long uuCt = 0L;
                if (lastDtState == null) {
                    lastState.update(lastDt);
                    uuCt = 1L;
                } else {
                    if (!lastDtState.equals(lastDt)) {
                        lastState.update(lastDt);
                        uuCt = 1L;
                        if ((ts - DateFormatUtil.toTs(lastDt)) / (1000 * 60 * 60 * 24) > 7) {
                            backCt = 1L;
                        }
                    }
                }

                out.collect(UserLoginBean.builder()
                        .backCt(backCt)
                        .uuCt(uuCt)
                        .ts(ts)
                        .build());
            }
        });

        //TODO 7 开窗聚合
        AllWindowedStream<UserLoginBean, TimeWindow> windowedStream = flatMap1.windowAll(TumblingEventTimeWindows.of(Time.seconds(10L)));
        SingleOutputStreamOperator<UserLoginBean> reduce = windowedStream.reduce(new ReduceFunction<UserLoginBean>() {
            @Override
            public UserLoginBean reduce(UserLoginBean value1, UserLoginBean value2) throws Exception {
                value1.setBackCt(value1.getBackCt() + value2.getBackCt());
                value1.setUuCt(value1.getUuCt() + value2.getUuCt());
                return value1;
            }
        }, new AllWindowFunction<UserLoginBean, UserLoginBean, TimeWindow>() {
            @Override
            public void apply(TimeWindow window, Iterable<UserLoginBean> values, Collector<UserLoginBean> out) throws Exception {
                UserLoginBean next = values.iterator().next();
                next.setStt(DateFormatUtil.toYmdHms(window.getStart()));
                next.setEdt(DateFormatUtil.toYmdHms(window.getEnd()));
                next.setTs(System.currentTimeMillis());
                out.collect(next);
            }
        });

        reduce.print("reduce>>>>>");
        //TODO 8 写入 clickhouse
        reduce.addSink(MyClickHouseUtil.<UserLoginBean>getSink("insert into dws_user_user_login_window values(?,?,?,?,?)"));

        env.execute(groupId);
    }
}
